package com.cap.dreamcircle.View;

import android.animation.ValueAnimator;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cap.dreamcircle.App.App;
import com.cap.dreamcircle.Base.BaseActivity;
import com.cap.dreamcircle.Model.Bean.DreamRecordsMonthlyBean;
import com.cap.dreamcircle.Model.Bean.DreamRecordsMonthlyEntity;
import com.cap.dreamcircle.Model.Bean.GridCalenderDateEntity;
import com.cap.dreamcircle.Model.IDreamModel;
import com.cap.dreamcircle.Model.Impl.DreamModelImpl;
import com.cap.dreamcircle.R;
import com.cap.dreamcircle.Utils.DateUtil;
import com.cap.dreamcircle.Utils.DisplayUtil;
import com.cap.dreamcircle.Utils.ToastUtils;
import com.cap.dreamcircle.Utils.TransformUtils;
import com.cap.dreamcircle.View.Adapter.CalendarGridViewAdapter;
import com.cap.dreamcircle.Widget.CalendarGridView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Subscriber;

/**
 * Created by liucxu on 2017/8/31.
 */

public class CalenderDreamsActivity extends BaseActivity {
    @BindView(R.id.layout_back)
    LinearLayout layout_back;
    @BindView(R.id.tv_title)
    TextView tv_title;

    @BindView(R.id.layout_pre_year)
    RelativeLayout layout_pre_year;
    @BindView(R.id.layout_next_year)
    RelativeLayout layout_next_year;
    @BindView(R.id.tv_current_year)
    TextView tv_current_year;

    @BindView(R.id.layout_pre_month)
    RelativeLayout layout_pre_month;
    @BindView(R.id.tv_pre_month)
    TextView tv_pre_month;
    @BindView(R.id.layout_current_month)
    RelativeLayout layout_current_month;
    @BindView(R.id.tv_current_month)
    TextView tv_current_month;
    @BindView(R.id.layout_next_month)
    RelativeLayout layout_next_month;
    @BindView(R.id.tv_next_month)
    TextView tv_next_month;

    @BindView(R.id.grid_view_calender)
    CalendarGridView grid_view_calender;

    @BindView(R.id.layout_good_dream_percent)
    RelativeLayout layout_good_dream_percent;
    @BindView(R.id.layout_normal_dream_percent)
    LinearLayout layout_normal_dream_percent;
    @BindView(R.id.layout_bad_dream_percent)
    RelativeLayout layout_bad_dream_percent;

    private Calendar calendar;
    private GridCalenderDateEntity showDateEntity;
    private int pre_month = 0;
    private int current_month = 0;
    private int next_month = 0;
    private static final int ROWS = 6;
    private static final int COLUMNS = 7;
    private List<GridCalenderDateEntity> datas = new ArrayList<>();
    private CalendarGridViewAdapter calendarAdapter;
    private IDreamModel model;
    private int goodTypeCount;
    private int badTypeCount;
    private int commonTypeCount;

    @Override
    public int getLayoutId() {
        return R.layout.activity_calender_dreams;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        layout_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                App.GetInstance().finishActivity(CalenderDreamsActivity.this);
            }
        });
        tv_title.setText("日历");
    }

    @Override
    public void setupData() {
        model = new DreamModelImpl();
        calendar = Calendar.getInstance();
        showDateEntity = new GridCalenderDateEntity(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, DateUtil.getCurrentMonthDay());
        calendarAdapter = new CalendarGridViewAdapter(this, datas);
        grid_view_calender.setAdapter(calendarAdapter);
        initViews();
    }

    private void initViews() {
        tv_current_year.setText(showDateEntity.getYear() + "");
        current_month = showDateEntity.getMonth();
        if (current_month == 1) {
            pre_month = 12;
            next_month = 2;
        } else {
            pre_month = current_month - 1;
            next_month = current_month + 1;
        }
        tv_pre_month.setText(pre_month + "");
        tv_current_month.setText(current_month + "");
        tv_next_month.setText(next_month + "");
//        refreshGridView();
        //点击了上一年
        layout_pre_year.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDateEntity = new GridCalenderDateEntity(showDateEntity.getYear() - 1, showDateEntity.getMonth(), showDateEntity.getDay());
                tv_current_year.setText(showDateEntity.getYear() + "");
                datas.clear();
                refreshGridView();
                showAnimationToLeft();
            }
        });
        //点击了下一年
        layout_next_year.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (Calendar.getInstance().get(Calendar.YEAR) > showDateEntity.getYear()) {
                showDateEntity = new GridCalenderDateEntity(showDateEntity.getYear() + 1, showDateEntity.getMonth(), showDateEntity.getDay());
                tv_current_year.setText(showDateEntity.getYear() + "");
                datas.clear();
                refreshGridView();
                showAnimationToRight();
//                }
            }
        });
        //点击了上一个月
        layout_pre_month.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //当前月份是1月，同时点击了上一个月,这个时候需要切换到12月并且年份减1
                if (showDateEntity.getMonth() == 1) {
                    showDateEntity = new GridCalenderDateEntity(showDateEntity.getYear() - 1, 12, 1);
                    tv_current_year.setText((showDateEntity.getYear()) + "");
                    tv_pre_month.setText((showDateEntity.getMonth() - 1) + "");
                    tv_current_month.setText(showDateEntity.getMonth() + "");
                    tv_next_month.setText(1 + "");
                    datas.clear();
                    refreshGridView();
                } else if (showDateEntity.getMonth() == 2) {
                    showDateEntity = new GridCalenderDateEntity(showDateEntity.getYear(), 1, 1);
                    tv_pre_month.setText(12 + "");
                    tv_current_month.setText(1 + "");
                    tv_next_month.setText(2 + "");
                    datas.clear();
                    refreshGridView();
                } else if (showDateEntity.getMonth() == 12) {
                    showDateEntity = new GridCalenderDateEntity(showDateEntity.getYear(), 11, 1);
                    tv_pre_month.setText((showDateEntity.getMonth() - 1) + "");
                    tv_current_month.setText(11 + "");
                    tv_next_month.setText(12 + "");
                    datas.clear();
                    refreshGridView();
                } else {
                    showDateEntity = new GridCalenderDateEntity(showDateEntity.getYear(), showDateEntity.getMonth() - 1, 1);
                    tv_pre_month.setText((showDateEntity.getMonth() - 1) + "");
                    tv_current_month.setText(showDateEntity.getMonth() + "");
                    tv_next_month.setText((showDateEntity.getMonth() + 1) + "");
                    datas.clear();
                    refreshGridView();
                }
                showAnimationToLeft();
            }
        });

        //点击了下一个月
        layout_next_month.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if ((showDateEntity.getYear() < Calendar.getInstance().get(Calendar.YEAR)) || ((showDateEntity.getYear() - Calendar.getInstance().get(Calendar.YEAR) == 0) && (showDateEntity.getMonth() < (calendar.get(Calendar.MONTH)+1)))) {
                //当前月份是1月，同时点击了下一个月,这个时候需要切换到12月并且年份减1
                if (showDateEntity.getMonth() == 1) {
                    showDateEntity = new GridCalenderDateEntity(showDateEntity.getYear(), 2, 1);
                    tv_pre_month.setText((showDateEntity.getMonth() - 1) + "");
                    tv_current_month.setText(showDateEntity.getMonth() + "");
                    tv_next_month.setText((showDateEntity.getMonth() + 1) + "");
                    datas.clear();
                    refreshGridView();
                } else if (showDateEntity.getMonth() == 11) {
                    showDateEntity = new GridCalenderDateEntity(showDateEntity.getYear(), 12, 1);
                    tv_pre_month.setText(11 + "");
                    tv_current_month.setText(12 + "");
                    tv_next_month.setText(1 + "");
                    datas.clear();
                    refreshGridView();
                } else if (showDateEntity.getMonth() == 12) {
                    showDateEntity = new GridCalenderDateEntity(showDateEntity.getYear() + 1, 1, 1);
                    tv_current_year.setText((showDateEntity.getYear()) + "");
                    tv_pre_month.setText(12 + "");
                    tv_current_month.setText(showDateEntity.getMonth() + "");
                    tv_next_month.setText((showDateEntity.getMonth() + 1) + "");
                    datas.clear();
                    refreshGridView();
                } else {
                    showDateEntity = new GridCalenderDateEntity(showDateEntity.getYear(), showDateEntity.getMonth() + 1, 1);
                    tv_pre_month.setText((showDateEntity.getMonth() - 1) + "");
                    tv_current_month.setText(showDateEntity.getMonth() + "");
                    tv_next_month.setText((showDateEntity.getMonth() + 1) + "");
                    datas.clear();
                    refreshGridView();
                }
                showAnimationToRight();
//                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        datas.clear();
        refreshGridView();
    }

    private void refreshGridView() {
        int lastMonthDays = DateUtil.getMonthDays(showDateEntity.getYear(),
                showDateEntity.getMonth() - 1); // 上个月的天数
        int currentMonthDays = DateUtil.getMonthDays(showDateEntity.getYear(),
                showDateEntity.getMonth()); // 当前月的天数
        int firstDayWeek = DateUtil.getWeekDayFromDate(showDateEntity.getYear(),
                showDateEntity.getMonth());//获取设置的当月的1号是星期几
        int day = 0;
        for (int row = 0; row < ROWS; row++) {
            for (int column = 0; column < COLUMNS; column++) {
                int position = column + row * COLUMNS; // 单元格位置
                //上月的数据
                if (position < firstDayWeek) {
                    GridCalenderDateEntity entity = new GridCalenderDateEntity(showDateEntity.getYear(),
                            showDateEntity.getMonth() - 1, lastMonthDays
                            - (firstDayWeek - position - 1));
                    datas.add(entity);
                }
                //本月的数据
                if ((position >= firstDayWeek) && (position < firstDayWeek + currentMonthDays)) {
                    day++;
                    GridCalenderDateEntity entity = new GridCalenderDateEntity(showDateEntity.getYear(),
                            showDateEntity.getMonth(), day);
                    entity.setCurrentMonth(true);
                    datas.add(entity);
                }
                //下月数据
                if (position >= (firstDayWeek + currentMonthDays)) {
                    GridCalenderDateEntity entity = new GridCalenderDateEntity(showDateEntity.getYear(),
                            showDateEntity.getMonth() + 1, position - firstDayWeek
                            - currentMonthDays + 1);
                    datas.add(entity);
                }
            }
        }
        requestMonthlyData();
    }


    private void requestMonthlyData() {
        model.RequestDreamRecordsMonthly(showDateEntity.getYear() + "", showDateEntity.getMonth() + "").compose(TransformUtils.<DreamRecordsMonthlyBean>defaultSchedulers()).subscribe(new Subscriber<DreamRecordsMonthlyBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                calendarAdapter.setDatas(datas);
                layout_good_dream_percent.setVisibility(View.GONE);
                layout_normal_dream_percent.setVisibility(View.GONE);
                layout_bad_dream_percent.setVisibility(View.GONE);
                goodTypeCount = 0;
                badTypeCount = 0;
                commonTypeCount = 0;
            }

            @Override
            public void onNext(DreamRecordsMonthlyBean dreamRecordsMonthlyBean) {
                if (dreamRecordsMonthlyBean.getCode() == 0) {
                    goodTypeCount = dreamRecordsMonthlyBean.getGoodTypeCount();
                    commonTypeCount = dreamRecordsMonthlyBean.getCommonTypeCount();
                    badTypeCount = dreamRecordsMonthlyBean.getBadTypeCount();
                    manageDatas(dreamRecordsMonthlyBean.getDreamRecord());
                } else {
                    ToastUtils.showShortToast(CalenderDreamsActivity.this, dreamRecordsMonthlyBean.getDesc());
                    calendarAdapter.setDatas(datas);
                    layout_good_dream_percent.setVisibility(View.GONE);
                    layout_normal_dream_percent.setVisibility(View.GONE);
                    layout_bad_dream_percent.setVisibility(View.GONE);
                    goodTypeCount = 0;
                    badTypeCount = 0;
                    commonTypeCount = 0;
                }
            }
        });
    }

    private int calculateDreamType(DreamRecordsMonthlyEntity entity) {
        //好 坏 普通 梦三种
        if ((entity.getBadTypeCount() > 0) && (entity.getGoodTypeCount() > 0) && (entity.getCommonTypeCount() > 0)) {
            return 1;
        } else {
            //好 坏 梦两种
            if ((entity.getBadTypeCount() > 0) && (entity.getGoodTypeCount() > 0)) {
                return 2;
            }
            //普通 坏 梦两种
            if ((entity.getBadTypeCount() > 0) && (entity.getCommonTypeCount() > 0)) {
                return 3;
            }
            //普通 好 梦两种
            if ((entity.getGoodTypeCount() > 0) && (entity.getCommonTypeCount() > 0)) {
                return 4;
            }
            //坏梦
            if (entity.getBadTypeCount() > 0) {
                return 5;
            }
            //普通梦
            if (entity.getCommonTypeCount() > 0) {
                return 6;
            }
            //好梦
            if (entity.getGoodTypeCount() > 0) {
                return 7;
            }
        }
        return -1;
    }

    private void manageDatas(List<DreamRecordsMonthlyEntity> entities) {
        HashMap<String, DreamRecordsMonthlyEntity> values = new HashMap<>();
        if (entities != null) {
            for (int index = 0; index < entities.size(); index++) {
                values.put(entities.get(index).getDay() + "", entities.get(index));
            }
        }
        for (int index = 0; index < datas.size(); index++) {
            if (values.containsKey(datas.get(index).getDay() + "") && (datas.get(index).getMonth() == showDateEntity.getMonth())) {
                datas.get(index).setDreamType(calculateDreamType(values.get(datas.get(index).getDay() + "")));
            }
        }
        calendarAdapter.setDatas(datas);
        int sum = goodTypeCount + commonTypeCount + badTypeCount;
        if (sum == 0) {
            layout_good_dream_percent.setVisibility(View.GONE);
            layout_normal_dream_percent.setVisibility(View.GONE);
            layout_bad_dream_percent.setVisibility(View.GONE);
        } else {
            double percent_good = ((double) goodTypeCount) / (sum);
            double percent_normal = ((double) commonTypeCount) / (sum);
            double percent_bad = ((double) badTypeCount) / (sum);
            if (percent_good > 0) {
                layout_good_dream_percent.setVisibility(View.VISIBLE);
            } else {
                layout_good_dream_percent.setVisibility(View.GONE);
            }
            if (percent_normal > 0) {
                layout_normal_dream_percent.setVisibility(View.VISIBLE);
            } else {
                layout_normal_dream_percent.setVisibility(View.GONE);
            }
            if (percent_bad > 0) {
                layout_bad_dream_percent.setVisibility(View.VISIBLE);
            } else {
                layout_bad_dream_percent.setVisibility(View.GONE);
            }
            layout_good_dream_percent.getLayoutParams().width = (int) ((DisplayUtil.GetDisplayWidth() - DisplayUtil.dip2px(this, 30)) * (percent_good));
            layout_normal_dream_percent.getLayoutParams().width = (int) ((DisplayUtil.GetDisplayWidth() - DisplayUtil.dip2px(this, 30)) * (percent_normal));
            layout_bad_dream_percent.getLayoutParams().width = (int) ((DisplayUtil.GetDisplayWidth() - DisplayUtil.dip2px(this, 30)) * (percent_bad));
            layout_good_dream_percent.requestLayout();
            layout_normal_dream_percent.requestLayout();
            layout_bad_dream_percent.requestLayout();
        }
    }

    private void showAnimationToRight() {
        ValueAnimator showCalendarAnimation = ValueAnimator.ofFloat(0f, 1f).setDuration((long) (800));
        showCalendarAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float percent = (float) animation.getAnimatedValue();
                grid_view_calender.setX((percent * (DisplayUtil.GetDisplayWidth())) - (DisplayUtil.GetDisplayWidth()));
            }
        });
        showCalendarAnimation.start();
    }

    private void showAnimationToLeft() {
        ValueAnimator showCalendarAnimation = ValueAnimator.ofFloat(0f, 1f).setDuration((long) (800));
        showCalendarAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float percent = (float) animation.getAnimatedValue();
                grid_view_calender.setX((DisplayUtil.GetDisplayWidth()) - (percent * (DisplayUtil.GetDisplayWidth())));
            }
        });
        showCalendarAnimation.start();
    }
}
